import * as type from './actionTypes'
import axios from 'axios';
import { message } from 'antd'
import { hashHistory } from 'react-router'
import Auth from '@/auth/Auth'
import { Base64 } from '@/utils/tool'


const requestLogin = (creds) => ({
    type: type.LOGIN_REQUEST,
    isFetching: true,
    isAuthenticated: false,
    creds
})

const receiveLogin = (user) => ({
    type: type.LOGIN_SUCCESS,
    isFetching: false,
    isAuthenticated: true,
    user
})

const loginError = (message) => ({
    type: type.LOGIN_FAILURE,
    isFetching: false,
    isAuthenticated: false,
    message
})

//登录认证
export const loginUser = (creds) => {

    let url = '/jwt';

    return (dispatch) => {

        dispatch(requestLogin(creds));

        return axios.post(url, creds)
            .then(res => {
                // console.log(res)
                if(res.status === 200){
                    let _token = res.data.jwt; 
                    let str = new Base64().decode(_token.split('.')[1]);
                    let _str = unescape(str.trim().replace(/\\u/g, '%u'));
                    let user = JSON.parse(_str.slice(0,-2));

                    Auth.authenticateUser(_token)
                    hashHistory.push('/app/dashboard')
                    dispatch(receiveLogin(user))

                }else if(res.status === 400){
                    dispatch(loginError(res.data.error))
                    return Promise.reject(res.data)
                }
            })
            .catch(err => {
                console.log(err)
                // message.error("接口异常！")
            })
        };
        
  }